package com.ops.uitl.config;

import com.ops.uitl.common.Common;
import com.ops.uitl.data.DataMap;
import com.ops.uitl.data.DatasetList;
import com.ops.uitl.data.IData;
import com.ops.uitl.data.IDataset;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class TEXTConfig implements IConfig{
	private InputStream instream;

	public TEXTConfig(String file) throws Exception {
		this.instream = Common.getInstance().getClassResourceStream(file);
	}

	public String getProperty(String prop) throws Exception {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(instream));

			String temp = null;

			do{
				temp = br.readLine();
				if (temp == null) break;
				if (temp.startsWith("#")) continue;
				int index = temp.indexOf("=");
				if (index == -1) continue;
				String key = temp.substring(0,index).trim();
				String value = temp.substring(index+1).trim();
				if (key.equals(prop)) {
					br.close();
					return value;
				}
			}
			while(temp != null);
			br.close();
			return null;
		} catch (Exception e) {
			if (br != null) br.close();
			throw e;
		}

	}

	public List getLineList() throws Exception{
		BufferedReader br = null;
		ArrayList list = new ArrayList();
		try {
			br = new BufferedReader(new InputStreamReader(instream));
			String temp = br.readLine();
			while(temp != null){
				list.add(temp);
				temp = br.readLine();
			}
			return list;
		} catch (Exception e) {
			if (br != null) br.close();
			throw e;
		}
	}

	public IData getProperties(String prop) throws Exception {
		return new DataMap();
	}

	public void setProperty(String prop, String value) throws Exception {
	}

	public void save() throws Exception {
	}

	/**
	 * 用XPath格式查找元素
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public IDataset getElements(String path) throws Exception {
		return new DatasetList(getLineList());
	}
}
